package com.hepinghospital.user.ui.activity.nursing;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hepinghospital.user.R;
import com.hepinghospital.user.adapter.ConsumeMaterialAdapter;
import com.hepinghospital.user.base.BaseActivity;
import com.hepinghospital.user.base.BaseApplication;
import com.hepinghospital.user.ui.dialog.RulesDialogFragment;
import com.hepinghospital.user.util.DataUtil;
import com.hepinghospital.user.util.ToastUtil;
import com.rest.business.RestProxy;
import com.rest.observer.BaseObserver;
import com.rest.response.MaterialBean;
import com.rest.response.NursingOrderDetailResponse;
import com.rest.response.WxPayBean;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @Description: 我de护理
 * @Author: lzp
 * @CreateDate: 2022/3/11 9:44
 * @UpdateRemark: 更新说明
 */
public class NursingOrderDetailActivity extends BaseActivity {
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_patient_name)
    TextView tvPatientName;
    @BindView(R.id.tv_patient_sex)
    TextView tvPatientSex;
    @BindView(R.id.tv_patient_age)
    TextView tvPatientAge;
    @BindView(R.id.tv_patient_phone)
    TextView tvPatientPhone;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.tv_dateTime)
    TextView tvDateTime;
    @BindView(R.id.tv_project)
    TextView tvProject;
    @BindView(R.id.cb_agree)
    CheckBox cbAgree;
    @BindView(R.id.tv_option1)
    TextView tvOption1;
    @BindView(R.id.tv_option2)
    TextView tvOption2;
    @BindView(R.id.tv_option3)
    TextView tvOption3;
    @BindView(R.id.tv_option4)
    TextView tvOption4;
    @BindView(R.id.tv_option5)
    TextView tvOption5;
    @BindView(R.id.ll_wait)
    LinearLayout llWait;
    @BindView(R.id.cl_nurse_layout)
    ConstraintLayout clNurseLayout;
    @BindView(R.id.ll_consumables)
    LinearLayout llConsumables;
    @BindView(R.id.ll_evaluate)
    LinearLayout llEvaluate;
    @BindView(R.id.ll_pay_layout)
    LinearLayout llPayLayout;
    @BindView(R.id.cl_bottom_pay)
    ConstraintLayout clBottomPay;
    @BindView(R.id.tv_total)
    TextView tvTotal;
    @BindView(R.id.tv_traffic)
    TextView tvTraffic;
    @BindView(R.id.ll_middle_total)
    LinearLayout llMiddleTotal;
    @BindView(R.id.tv_evaluate)
    TextView tvEvaluate;
    @BindView(R.id.ratingBar)
    RatingBar ratingBar;
    @BindView(R.id.tv_nurse_phone)
    TextView tvNursePhone;
    @BindView(R.id.recyclerView_consume_material)
    RecyclerView recyclerViewConsumeMaterial;
    @BindView(R.id.tv_total_amount)
    TextView tvTotalAmount;
    @BindView(R.id.tv_wait_pay)
    TextView tvWaitPay;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_agree)
    TextView tvAgree;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    NursingOrderDetailResponse nursingOrderDetail;
    int amount;
    String appointmentId, orderId, nursePhone;
    IWXAPI wxApi;
    String itemCode;

    private RulesDialogFragment mRulesDialogFragment;

    static WeakReference<Activity> mActivity = null;
    ConsumeMaterialAdapter consumeMaterialAdapter;
    List<MaterialBean> materialBeanList = new ArrayList<>();

    @Override
    protected void initViews() {
        tvTitle.setText("订单详情");
        AppointProjectListActivity.clsoeSelf();
        AppointStep1Activity.clsoeSelf();
        AppointStep2Activity.clsoeSelf();
        AppointStep3Activity.clsoeSelf();

        tvNursePhone.setOnClickListener(v -> callPhone(nursePhone));
        consumeMaterialAdapter = new ConsumeMaterialAdapter(materialBeanList);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        recyclerViewConsumeMaterial.setLayoutManager(linearLayoutManager);
        recyclerViewConsumeMaterial.setAdapter(consumeMaterialAdapter);
        consumeMaterialAdapter.addChildClickViewIds(R.id.tv_consumeMaterials_pay);
        consumeMaterialAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            nurseRequestPay(materialBeanList.get(position).getOrderId() + "", materialBeanList.get(position).getOrderAmount());
//            ToastUtil.showToast(mContext, "支付耗材");
        });
        tvAgree.setOnClickListener(v -> {
            if (!TextUtils.isEmpty(itemCode)) {
                showRulesDialogFragment();
            }
        });
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(refreshLayout -> {
            getOrderDetail(Long.parseLong(appointmentId));
        });
    }

    @Override
    protected void initData() {
        mActivity = new WeakReference<>(this);
        appointmentId = getIntent().getStringExtra("appointmentId");
        getOrderDetail(Long.parseLong(appointmentId));
    }


    @Override
    protected int getLayoutResource() {
        return R.layout.activity_nursing_order_detail;
    }


    private void showRulesDialogFragment() {
        mRulesDialogFragment = RulesDialogFragment.newInstance(itemCode);
        mRulesDialogFragment.setmListener(() -> mRulesDialogFragment.dismiss());
        mRulesDialogFragment.show(getSupportFragmentManager(), "mSchudeleDialogFragment");
    }

    /**
     * 获取订单详情
     *
     * @param appointmentId 预约单id用此打开详情
     */
    private void getOrderDetail(long appointmentId) {
        RestProxy.getInstance().getNursingOrderDetail(appointmentId, new BaseObserver<NursingOrderDetailResponse>() {
            @Override
            public void onError(@NonNull Throwable e) {
                super.onError(e);
                ToastUtil.onError(NursingOrderDetailActivity.this, e);
            }

            @SuppressLint("SetTextI18n")
            @Override
            public void onSuccess(NursingOrderDetailResponse result) {
                refreshLayout.finishRefresh(true);
                nursingOrderDetail = result;
                itemCode = nursingOrderDetail.getChargeItemCode();
//                materialBeanList.addAll(handleConsumeMaterials(result.getConsumeMaterials()));
                materialBeanList.addAll(DataUtil.INSTANCE.handleConsumeMaterials(result.getConsumeMaterials()));
                consumeMaterialAdapter.notifyDataSetChanged();

                tvPatientName.setText("姓名：" + result.getPatientName());
                tvPatientSex.setText("性别：" + result.getSex());
                tvPatientAge.setText("年龄：" + result.getAge() + "岁");
                tvPatientPhone.setText("联系方式：" + result.getPatientPhone());
                tvAddress.setText("地址：" + result.getAdress());
                tvDateTime.setText("预约时间：" + result.getAppointmentTime());
                tvProject.setText(result.getProjectTitle());

                tvOption1.setText("眼睛是否红、肿、痛：" + (result.getIsEyeRed() == 0 ? "否" : "是"));
                tvOption2.setText("有无分泌物：" + (result.getIsSecretion() == 0 ? "无分泌物" : "有分泌物"));
                tvOption3.setText("睫毛有无倒睫：" + (result.getIsSecretion() == 0 ? "无倒睫" : "有倒睫"));
                tvOption4.setText("泪道是否通畅：" + (result.getIsUnobstructed() == 0 ? "不通畅" : "通畅"));
                tvOption5.setText("眼部是否有缝线：" + (result.getIsSuture() == 0 ? "无缝线" : "有缝线"));

                tvEvaluate.setText(result.getCommentContent());
                int score = result.getCommentScore().isEmpty() ? 0 : Integer.parseInt(result.getCommentScore());
                ratingBar.setRating(score);

                amount = (int) (Float.parseFloat(result.getOrderAmount()) * 100);
                orderId = result.getOrderId();
                nursePhone = result.getNursePhone();

                switch (nursingOrderDetail.getAppointmentStatus()) {
                    case 0:
                        llPayLayout.setVisibility(View.VISIBLE);
                        clBottomPay.setVisibility(View.VISIBLE);
                        llWait.setVisibility(View.GONE);
                        clNurseLayout.setVisibility(View.GONE);
                        llEvaluate.setVisibility(View.GONE);
                        llMiddleTotal.setVisibility(View.GONE);
                        break;
                    case 1:
                    case 2:
                        llPayLayout.setVisibility(View.GONE);
                        clBottomPay.setVisibility(View.GONE);
                        llWait.setVisibility(View.VISIBLE);
                        clNurseLayout.setVisibility(View.GONE);
                        llEvaluate.setVisibility(View.GONE);
                        llMiddleTotal.setVisibility(View.GONE);
                        break;
                    case 3:
                        llPayLayout.setVisibility(View.GONE);
                        clBottomPay.setVisibility(View.GONE);
                        llWait.setVisibility(View.GONE);
                        clNurseLayout.setVisibility(View.VISIBLE);
                        tvName.setText(result.getNurseName());
                        llEvaluate.setVisibility(View.GONE);
                        llMiddleTotal.setVisibility(View.VISIBLE);
                        break;
                    case 4:
                        llPayLayout.setVisibility(View.GONE);
                        clBottomPay.setVisibility(View.GONE);
                        llWait.setVisibility(View.GONE);
                        clNurseLayout.setVisibility(View.GONE);
                        llEvaluate.setVisibility(View.GONE);
                        llMiddleTotal.setVisibility(View.GONE);
                        break;
                    case 5:
                        llPayLayout.setVisibility(View.GONE);
                        clBottomPay.setVisibility(View.GONE);
                        llWait.setVisibility(View.GONE);
                        clNurseLayout.setVisibility(View.VISIBLE);
                        tvName.setText(result.getNurseName());
                        tvNursePhone.setEnabled(false);
                        llEvaluate.setVisibility(View.VISIBLE);
                        llMiddleTotal.setVisibility(View.VISIBLE);
                        break;
                    default:
                        break;
                }

                if (result.getConsumeMaterials().isEmpty()) {
                    llConsumables.setVisibility(View.GONE);
                    tvWaitPay.setVisibility(View.GONE);
                } else {
                    llConsumables.setVisibility(View.VISIBLE);
                    if (consumeMaterialAdapter.show()) {
                        tvWaitPay.setText("含" + consumeMaterialAdapter.getWaitedTotalAmount() / 100 + "元待支付");
                    } else {
                        tvWaitPay.setVisibility(View.GONE);
                    }
                }

                SpannableStringBuilder spannable = new SpannableStringBuilder("合计：" + Double.parseDouble(result.getOrderAmount()) / 100 + "元");
                spannable.setSpan(new ForegroundColorSpan(ContextCompat.getColor(mContext, R.color.color_F54C4C)), 3, spannable.length() - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                tvTotal.setText(spannable);

                SpannableStringBuilder spannable1 = new SpannableStringBuilder("含交通费" + Double.parseDouble(result.getFare()) / 100 + "元");
                spannable1.setSpan(new ForegroundColorSpan(ContextCompat.getColor(mContext, R.color.color_FBAF57)), 4, spannable1.length() - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                tvTraffic.setText(spannable1);

                double totalAmount = Double.parseDouble(result.getOrderAmount()) + consumeMaterialAdapter.getConsumeMaterialAmount();

                SpannableStringBuilder spannable2 = new SpannableStringBuilder("合计：" + totalAmount / 100 + "元");
                spannable2.setSpan(new ForegroundColorSpan(ContextCompat.getColor(mContext, R.color.color_F54C4C)), 3, spannable2.length() - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                tvTotalAmount.setText(spannable2);
            }
        });
    }

    private void nurseRequestPay(String orderId, String orderAmount) {
        BaseApplication.currentOrderId = orderId;
        BaseApplication.diagnoseType = -1;
        BaseApplication.isNursingPay = true;
        RestProxy.getInstance().nurseRequestPay(orderId, orderAmount, new BaseObserver<WxPayBean>() {
            @Override
            public void onSuccess(WxPayBean wxPayBean) {
//                BaseApplication.currentWXId = wxPayBean.getAppid();
                wxApi = WXAPIFactory.createWXAPI(mContext, wxPayBean.getAppid());
//                // 将该app注册到微信
                wxApi.registerApp(wxPayBean.getAppid());
                PayReq request = new PayReq();
                request.appId = wxPayBean.getAppid();
                request.partnerId = wxPayBean.getPartnerid();
                request.prepayId = wxPayBean.getPrepayid();
                request.packageValue = "Sign=WXPay";
                request.nonceStr = wxPayBean.getNoncestr();
                request.timeStamp = wxPayBean.getTimestamp();
//                request.signType = wxPayBean.getGetType();
                request.sign = wxPayBean.getSign();
                wxApi.sendReq(request);
            }

            @Override
            public void onError(@NonNull Throwable e) {
                ToastUtil.onError(mContext, e);
            }
        });
    }

    @OnClick(R.id.tv_bottom_pay)
    public void onViewClicked() {
        if (!cbAgree.isChecked()) {
            ToastUtil.showToast(mContext, "请先阅读并勾选患者须知");
            return;
        }
        nurseRequestPay(orderId, amount + "");
    }

    /**
     * 拨打电话(跳转到拨号界面，用户手动点击拨打)
     *
     * @param phoneNum 电话号码
     */

    public void callPhone(String phoneNum) {
        Intent intent = new Intent(Intent.ACTION_DIAL);
        Uri data = Uri.parse("tel:" + phoneNum);
        intent.setData(data);
        startActivity(intent);
    }

    public static void clsoeSelf() {
        if (mActivity != null && mActivity.get() != null) {
            Activity context = mActivity.get();
            context.finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mActivity != null) {
            mActivity.clear();
            mActivity = null;
        }
    }
}
